import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Space, Button, Pagination, message, Modal, Tooltip, Card } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import DraggableTable from '@/components/DraggableTable';
import DataTableActions from './DataTableActions';
import request from '@/utils/request';
import { useNavigate } from 'react-router-dom';
import TopActionBar from './TopActionBar';
import { restoreColumns, saveColumns, getSortState } from '@/utils/columnStorage';

// 发布状态映射
const releaseStatusMap = {
	3: '发布中',
	2: '未发布',
	1: '发布成功',
	0: '发布失败'
  };
  const releaseStatusColor = {
	5: 'gray',
	3: 'blue',
	2: 'orange',
	1: 'green',
	0: 'red'
  };

// 其他数据面板，负责右侧所有业务逻辑
const OtherDataPanel = ({ otherDataKey, visible }) => {
  const navigate = useNavigate();
  // 关键字搜索
  const [searchKeyword, setSearchKeyword] = useState('');
  // 分页
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  // 表格数据
  const [tableData, setTableData] = useState([]);
  // loading
  const [tableLoading, setTableLoading] = useState(false);
  // 选中行
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  // 滚动高度
  const [tableScrollY, setTableScrollY] = useState(0);
  // data level信息
  const [dataLevel, setDataLevel] = useState({ level: 'all', count: 0, size: 0 });
  // 操作列折叠状态
  const [isActionColumnCollapsed, setIsActionColumnCollapsed] = useState(false);
  // 排序状态
  const [sortState, setSortState] = useState({ field: null, order: null });
  // 表格列
  const [columns, setColumns] = useState<any[]>([]);
  const tableContainerRef = useRef(null);
  // TopActionBar ref
  const topActionBarRef = useRef(null);
  
  // 手动归档相关状态
  const [manualArchiveModalVisible, setManualArchiveModalVisible] = useState(false);
  const [archivePath, setArchivePath] = useState('');
  const [archiveLoading, setArchiveLoading] = useState(false);
  
  
  // 添加 AbortController 引用
  const abortControllerRef = useRef(null);

  // 操作列渲染函数
  const renderActionColumn = (_, record) => {
    if (isActionColumnCollapsed) {
      return (
        <Space size="small" style={{ justifyContent: 'center' }}>
          <Button size="small" icon={<span>↓</span>} onClick={() => handleDownload(record)} title="下载" />
          <Button size="small" icon={<span>×</span>} danger onClick={() => handleDelete(record)} title="删除" />
          {record.is_favorites ? (
            <Button 
              size="small" 
              icon={<span style={{ color: '#ffd700' }}>★</span>} 
              onClick={() => handleUnfavorite(record)}
              title="取消收藏"
            />
          ) : (
            <Button size="small" icon={<span>★</span>} onClick={() => handleFavorite(record)} title="收藏" />
          )}
        </Space>
      );
    }
    
    return (
      <Space>
        <Button size="small" onClick={() => handleDownload(record)}>
          下载
        </Button>
        <Button size="small" danger onClick={() => handleDelete(record)}>
          删除
        </Button>
        {record.is_favorites ? (
          <Button 
            size="small" 
            icon={<span style={{ color: '#ffd700' }}>★</span>} 
            onClick={() => handleUnfavorite(record)}
          >
            收藏
          </Button>
        ) : (
          <Button size="small" icon={<span>★</span>} onClick={() => handleFavorite(record)}>
            收藏
          </Button>
        )}
      </Space>
    );
  };
  
  // 监听操作列变化
  useEffect(() => {
    setColumns((prevColumns) => {
      if (!prevColumns) return prevColumns;
      return prevColumns.map((col) => {
        if (col.key === 'action') {
          return {
            ...col,
            width: isActionColumnCollapsed ? 100 : 220,
            render: renderActionColumn
          };
        }
        return col;
      });
    });
  }, [isActionColumnCollapsed]);

  // 保存列配置到localStorage
  useEffect(() => {
    if (columns.length > 0) {
      const tableKey = 'other_data_table';
      saveColumns(columns, tableKey, sortState);
    }
  }, [columns, sortState]);

  // 列
  const defaultColumns = [
    {
      title: '文件名',
      dataIndex: 'file_name',
      key: 'file_name',
      width: 180,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '文件路径',
      dataIndex: 'file_path',
      key: 'file_path',
      width: 180,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '文件大小',
      dataIndex: 'data_size',
      key: 'data_size',
      width: 80,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '归档时间',
      dataIndex: 'archive_time',
      key: 'archive_time',
      width: 180,
      ellipsis: { showTitle: false },
      render: (text) => (
        <Tooltip title={text}>
          <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
        </Tooltip>
      )
    },
    {
      title: '发布状态',
      dataIndex: 'release_status',
      key: 'release_status',
      width: 100,
      render: (value) => (
        <span style={{ color: releaseStatusColor[value] || 'gray' }}>
          {releaseStatusMap[value] || '未知'}
        </span>
      )
    },
    {
      title: '状态',
      dataIndex: 'bk_pstate',
      key: 'bk_pstate',
      width: 80,
      ellipsis: { showTitle: false },
      render: (value) => (value === 1 ? '已备份' : '未备份'),
    }
  ];

  // 监听表格容器高度变化，动态设置滚动高度
  const calculateTableScrollHeight = () => {
    if (visible && tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 42;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  useEffect(() => {
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  // 组件卸载时取消所有请求
  useEffect(() => {
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  useEffect(() => {
    calculateTableScrollHeight();
  }, [visible]);

  // 监听数据key变化，重置分页和关键字
  useEffect(() => {
    if (otherDataKey) {
      // 取消正在进行的请求
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      // 重置状态
      setCurrent(1);
      setSearchKeyword('');
      setSelectedRowKeys([]);
    }
  }, [otherDataKey]);

  // 拉取数据和动态列
  const fetchData = async (curPage = current, size = pageSize, search = searchKeyword) => {
    if (!otherDataKey) return;
    
    // 取消之前的请求
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    abortControllerRef.current = new AbortController();
    const signal = abortControllerRef.current.signal;
    
    setTableLoading(true);
    try {
      const res = await request.get('/Management/AdvancedDataList', {
        params: {
          file_name: search,
          advanced_data_id: 1,
          data_key: otherDataKey,
          page_size: size,
          page: curPage
        },
        signal
      });
      if (res.status === 200 && res.data.data) {
        const { columns: colArr = [], list = [], count = 0, data_level } = res.data.data;
        // 更新data_level信息
        if (data_level) {
          setDataLevel(data_level);
        }
        // 合并默认字段和后端字段，默认字段优先，去重
        const allColArr = [
          ...defaultColumns.map(col => col.dataIndex),
          ...colArr.filter(col => !defaultColumns.some(def => def.dataIndex === col))
        ];
        // 动态生成columns
        const dynamicColumns = allColArr.map((col) => {
          const defaultCol = defaultColumns.find(def => def.dataIndex === col);
          if (defaultCol) return defaultCol;
          return {
            title: col,
            dataIndex: col,
            key: col,
            width: 100,
            ellipsis: { showTitle: false },
            render: (text) => (
              <Tooltip title={text}>
                <div style={{ cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{text}</div>
              </Tooltip>
            )
          };
        });
        // 固定操作列
        dynamicColumns.push({
          title: '操作',
          key: 'action',
          width: isActionColumnCollapsed ? 100 : 220,
          fixed: 'right',
          align: 'center',
          render: renderActionColumn
        });
        // 从localStorage恢复列配置
        const tableKey = 'other_data_table';
        const restoredColumns = restoreColumns(dynamicColumns, tableKey);
        setColumns(restoredColumns);
        
        // 恢复排序状态
        const savedSortState = getSortState(tableKey);
        if (savedSortState) {
          setSortState(savedSortState);
        }
        // 数据加key
        const tableData = list.map((item, idx) => ({
          ...item,
          key: item.product_id ? item.product_id : `${otherDataKey}_${idx}`
        }));
        setTableData(tableData);
        setTotal(count);
      }
    } catch (e) {
      if (e.name === 'CanceledError' || e.name === 'AbortError') {
        return;
      }
      message.error(e?.message || '获取数据失败');
    } finally {
      setTableLoading(false);
    }
  };

  useEffect(() => {
    fetchData(current, pageSize, searchKeyword);
    // eslint-disable-next-line
  }, [otherDataKey, current, pageSize]);

  // 下载
  const handleDownload = (record) => {
    if (!record.product_id) {
      message.warning('缺少product_id，无法下载');
      return;
    }
    const url = request.getUrl(`/Management/Download?data_type=${record.data_type}&product_id=${record.product_id}`);
    window.open(url, '_blank');
  };

  // 删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件"${record.file_name || record['文件名']}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: [
              {
                data_type: record.data_type,
                product_id: record.product_id
              }
            ]
          };
          const res = await request.post('/Management/DataDelete', payload);
          if (res.status === 200) {
            message.success('删除成功');
            fetchData(current, pageSize, searchKeyword);
          }
        } catch (e) {
          message.error(e?.message || '删除失败');
        }
      }
    });
  };

  // 收藏
  const handleFavorite = async (record) => {
    if (!record.product_id) {
      message.warning('缺少product_id，无法收藏');
      return;
    }
    try {
      const payload = {
        files: [
          {
            data_type: record.data_type,
            product_id: record.product_id
          }
        ]
      };
      const res = await request.post('/Management/Favorites', payload);
      if (res.status === 200) {
        message.success('收藏成功');
        setTableData((prevData) => prevData.map((item) => (item.key === record.key ? { ...item, is_favorites: 1 } : item)));
      }
    } catch (e) {
      message.error(e?.message || '收藏失败');
    }
  };

  // 取消收藏
  const handleUnfavorite = async (record) => {
    if (!record.product_id) {
      message.warning('缺少product_id，无法取消收藏');
      return;
    }
    try {
      const res = await request.post('/Management/FavoritesCancel', {
        file_ids: [record.key]
      });
      if (res.status === 200) {
        message.success('取消收藏成功');
        setTableData((prevData) => prevData.map((item) => (item.key === record.key ? { ...item, is_favorites: 0 } : item)));
      }
    } catch (e) {
      message.error(e?.message || '取消收藏失败');
    }
  };


  // 手动归档
  const handleManualArchive = () => {
    setManualArchiveModalVisible(true);
    setArchivePath('');
  };

  const handleArchiveSubmit = async () => {
    if (!archivePath.trim()) {
      message.error('请输入文件路径');
      return;
    }

    setArchiveLoading(true);
    try {
      const token = localStorage.getItem('token') || '';
      const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
      
      const response = await fetch(`${API_BASE_URL}/-/bin.manualArchiving.add_manual_archiving`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'token': token
        },
        body: JSON.stringify({
          path: archivePath.trim()
        })
      });

      if (!response.ok) {
        throw new Error(`API调用失败: ${response.statusText}`);
      }

      const result = await response.json();
      
      if (result && (result.code === 0 || result.code === 200)) {
        message.success('手动归档任务提交成功');
        setManualArchiveModalVisible(false);
        setArchivePath('');
      } else {
        message.error(`归档失败: ${result.msg || '未知错误'}`);
      }
    } catch (error) {
      console.error('手动归档失败:', error);
      message.error(`归档失败: ${error.message}`);
    } finally {
      setArchiveLoading(false);
    }
  };

  const handleArchiveCancel = () => {
    setManualArchiveModalVisible(false);
    setArchivePath('');
  };

  // 多选
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (keys) => {
      setSelectedRowKeys(keys);
    }
  };

  // 处理搜索
  const handleSearch = () => {
    setCurrent(1);
    fetchData(1, pageSize, searchKeyword);
  };

  // 处理清除
  const handleClear = () => {
    setSearchKeyword('');
    setCurrent(1);
    setTimeout(() => {
      fetchData(1, pageSize, '');
    }, 0);
  };

  // 格式化文件大小
  const formatFileSize = (size) => {
    if (size < 1024) {
      return size + ' B';
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(2) + ' KB';
    } else if (size < 1024 * 1024 * 1024) {
      return (size / (1024 * 1024)).toFixed(2) + ' MB';
    } else {
      return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
    }
  };

  return (
    <div
      className="data-management-right"
      style={{ ...{ flex: '1', overflow: 'auto', minWidth: 0 }, display: visible ? 'flex' : 'none' }}
    >
      {/* 顶部搜索区 */}
      <Form layout="inline" className="filter-form">
        <Form.Item style={{ width: 320 }} label="关键字">
          <Input
            placeholder="请输入关键字进行检索"
            value={searchKeyword}
            onChange={e => setSearchKeyword(e.target.value)}
            style={{ width: '100%' }}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={handleSearch}>
              筛选
            </Button>
            <Button onClick={handleClear}>清除</Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 固定项筛选条 */}
      <div className="fixed-filter-tabs">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
          <div
            style={{
              overflowX: 'auto',
              whiteSpace: 'nowrap',
              overflowY: 'hidden',
              marginRight: 10,
              lineHeight: '22px'
            }}
          >
            <span className="filter-tab-item active">
              {dataLevel.level === 'all' ? '全部' : dataLevel.level}({dataLevel.count}/{formatFileSize(dataLevel.size)})
            </span>
          </div>
          <div>
            <TopActionBar 
              ref={topActionBarRef}
              onConvertSuccess={() => {
                // 转换成功后刷新数据
                fetchData();
              }}
            />
          </div>
        </div>
      </div>

      {/* 数据表格 */}
      <div ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
        <DraggableTable
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          pagination={false}
          tableLayout="fixed"
          style={{ flex: 1 }}
          scroll={{ y: tableScrollY, x: 'max-content' }}
          bordered
          size="small"
          loading={tableLoading}
          rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
          onColumnsChange={(columns) => {
            setColumns(columns);
          }}
        />
        <Button
          type="normal"
          size="small"
          icon={isActionColumnCollapsed ? <LeftOutlined /> : <RightOutlined />}
          onClick={() => setIsActionColumnCollapsed(!isActionColumnCollapsed)}
          style={{
            position: 'absolute',
            top: '8px',
            right: isActionColumnCollapsed ? '85px' : '165px',
            zIndex: 1000,
            borderRadius: '4px',
            fontSize: '12px',
            color: '#1890ff',
            gap: '0px',
          }}
        >
          {isActionColumnCollapsed ? '' : '收起'}
        </Button>
      </div>
      {/* 表格下方操作按钮和分页 */}
      <div
        className="table-footer-bar"
        style={{ marginTop: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div className="action-buttons" style={{ marginBottom: 0, boxShadow: 'none', borderRadius: 0, background: 'none', padding: 0 }}>
          <DataTableActions
            advanced={true}
            selectedRowKeys={selectedRowKeys}
            setSelectedRowKeys={setSelectedRowKeys}
            dataKey={otherDataKey}
            tableData={tableData}
            filterParams={{}}
            fetchTableData={() => fetchData(current, pageSize, searchKeyword)}
            fetchDataLevel={() => {}}
            fetchFilterOptions={() => {}}
            type="other"
            columns={columns}
            refreshDownloadingCount={() => {
              try { (topActionBarRef.current as any)?.refreshDownloadingCount?.(); } catch(e) {}
            }}
          />
        </div>
        <Pagination
          className="science-data-pagination"
          current={current}
          pageSize={pageSize}
          total={total}
          simple
          showSizeChanger
          style={{ 
            marginLeft: 10,
            paddingRight: 0,
            marginTop: 0, 
            whiteSpace: 'nowrap', 
            display: 'flex', 
            flexDirection: 'row', 
            alignItems: 'center' 
          }}
          pageSizeOptions={['10', '20', '50']}
          onChange={(page, size) => {
            setCurrent(page);
            setPageSize(size);
          }}
          showTotal={(total) => `共${total}条`}
        />
      </div>

      {/* 手动归档弹窗 */}
      <Modal
        title="手动归档"
        open={manualArchiveModalVisible}
        onOk={handleArchiveSubmit}
        onCancel={handleArchiveCancel}
        confirmLoading={archiveLoading}
        okText="开始归档"
        cancelText="取消"
        width={600}
      >
        <Form layout="vertical">
          <Form.Item 
            label="文件路径" 
            required
            help="请输入需要归档的文件或目录的完整路径"
          >
            <Input.TextArea
              value={archivePath}
              onChange={(e) => setArchivePath(e.target.value)}
              placeholder=""
              rows={3}
              maxLength={500}
              showCount
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default OtherDataPanel; 